<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,学习笔记,量化投资,Backtrader," />










<meta name="description" content="从开始学量化交易以来，我先后试了bt和pyalgotrade两个框架，都有一些问题。最近得知backtrader这个单机的量化投资回测框架，试了一下能装上，就尝试一下吧。本文是我看官方文档并进行尝试的记录。文档地址: https:&#x2F;&#x2F;www.backtrader.com&#x2F;docu&#x2F;这个框架的主要目标就是易用。运行框架的基本步骤:1.创建一个策略①确定可能需要调整的参数。②实现策略中需要的指标。③写">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记69——量化回测框架backtrader">
<meta property="og:url" content="https://zwdnet.github.io/2020/06/26/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B069%E2%80%94%E2%80%94%E9%87%8F%E5%8C%96%E5%9B%9E%E6%B5%8B%E6%A1%86%E6%9E%B6backtrader/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="从开始学量化交易以来，我先后试了bt和pyalgotrade两个框架，都有一些问题。最近得知backtrader这个单机的量化投资回测框架，试了一下能装上，就尝试一下吧。本文是我看官方文档并进行尝试的记录。文档地址: https:&#x2F;&#x2F;www.backtrader.com&#x2F;docu&#x2F;这个框架的主要目标就是易用。运行框架的基本步骤:1.创建一个策略①确定可能需要调整的参数。②实现策略中需要的指标。③写">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/44/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-06-26T04:02:52.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="Backtrader">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/44/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/06/26/量化投资学习笔记69——量化回测框架backtrader/"/>





  <title>量化投资学习笔记69——量化回测框架backtrader | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/06/26/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B069%E2%80%94%E2%80%94%E9%87%8F%E5%8C%96%E5%9B%9E%E6%B5%8B%E6%A1%86%E6%9E%B6backtrader/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记69——量化回测框架backtrader</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-06-26T04:02:52+00:00">
                2020-06-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  27
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>从开始学量化交易以来，我先后试了bt和pyalgotrade两个框架，都有一些问题。最近得知backtrader这个单机的量化投资回测框架，试了一下能装上，就尝试一下吧。本文是我看官方文档并进行尝试的记录。<br>文档地址: <a target="_blank" rel="noopener" href="https://www.backtrader.com/docu/">https://www.backtrader.com/docu/</a><br>这个框架的主要目标就是易用。<br>运行框架的基本步骤:<br>1.创建一个策略<br>①确定可能需要调整的参数。<br>②实现策略中需要的指标。<br>③写买入卖出逻辑。<br>2.创建一个回测引擎(Cerebro Engine)<br>①插入一个策略。<br>②加载并插入一个数据源。<br>③运行引擎。<br>④可视化回测结果(cerebro.plot())<br>安装: pip install backtrader<br>backtrader的两个基本概念:<br>1.Lines(不知道咋翻了)<br>数据源，指标和策略有Lines。一系列在时间上连续的数据点称为线。数据源含有”Open, High, Low, Close, Volume, OpenInterest”六条线，如果加上日期就是七条。<br>2.0索引<br>在一条Line中，当前值的索引为0。最后输出值的索引为-1。即当前时刻的索引为0，当前时刻之前的时刻的索引为-1。更早的时刻可以用-2，-3等获得。<br>默认的，引擎会在后台建立broker实例，还有默认的初始金额，是1万货币单位。如果没改变，就会使用默认值。这会简化使用。<br>设置初始资金，用cerebro.broker.setcash()函数。<br>框架使用的数据源为bt.feeds，支持雅虎金融，谷歌金融等格式，对于国内常用的tushare，先保存为DataFrame，再用bt.feeds.PandasData()转换成数据源。要求是有’open’,’high’,’low’,’close’,’volume’,’openinterest’六列，其中’openinterest’可设为0。另外DataFrame需要以datetime类型的date列为索引。建立以后用cerebro.adddata()将数据载入引擎。<br>现在就实现第一个策略了，每个交易日都输出股价现值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># backtrader的第一个策略</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建一个策略</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt = <span class="literal">None</span></span>):</span></span><br><span class="line">        dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">        print(<span class="string">&quot;%s, %s&quot;</span> % (dt.isoformat(), txt))</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.log(<span class="string">&quot;Close, %.2f&quot;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    cerebro = bt.Cerebro()</span><br><span class="line">    cerebro.addstrategy(TestStrategy)</span><br><span class="line">    <span class="comment"># 加载数据</span></span><br><span class="line">    start = <span class="string">&quot;2019-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2019-12-31&quot;</span></span><br><span class="line">    df = ts.get_k_data(<span class="string">&quot;510300&quot;</span>, autype = <span class="string">&quot;qfq&quot;</span>, start = start,  end = end)</span><br><span class="line">    df.index = pd.to_datetime(df.date)</span><br><span class="line">    df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">    df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">    data = bt.feeds.PandasData(dataname = df, fromdate = datetime.datetime(<span class="number">2019</span>, <span class="number">1</span>, <span class="number">1</span>), todate = datetime.datetime(<span class="number">2019</span>, <span class="number">12</span>, <span class="number">31</span>))</span><br><span class="line">    cerebro.adddata(data)</span><br><span class="line">    <span class="comment"># 设置初始资金</span></span><br><span class="line">    cerebro.broker.setcash(<span class="number">100000.0</span>)</span><br><span class="line">    print(<span class="string">&quot;初始资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    cerebro.run()</span><br><span class="line">    print(<span class="string">&quot;期末资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">初始资金:<span class="number">100000.00</span></span><br><span class="line"><span class="number">2019</span>-01-02, Close, <span class="number">3.02</span></span><br><span class="line"><span class="number">2019</span>-01-03, Close, <span class="number">3.02</span></span><br><span class="line"><span class="number">2019</span>-01-04, Close, <span class="number">3.09</span></span><br><span class="line"><span class="number">2019</span>-01-07, Close, <span class="number">3.11</span></span><br><span class="line"><span class="number">2019</span>-01-08, Close, <span class="number">3.11</span></span><br><span class="line"><span class="number">2019</span>-01-09, Close, <span class="number">3.13</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">10</span>, Close, <span class="number">3.13</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">11</span>, Close, <span class="number">3.16</span></span><br><span class="line">......</span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">20</span>, Close, <span class="number">4.02</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">23</span>, Close, <span class="number">3.96</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">24</span>, Close, <span class="number">3.98</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">25</span>, Close, <span class="number">3.99</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">26</span>, Close, <span class="number">4.02</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">27</span>, Close, <span class="number">4.02</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">30</span>, Close, <span class="number">4.08</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, Close, <span class="number">4.10</span></span><br><span class="line">期末资金:<span class="number">100000.00</span></span><br></pre></td></tr></table></figure>
<p>框架的策略类有python的list数据，名为datas。其中第一个数据self.datas[0]是交易操作的默认数据并随策略保持同步。<br>self.dataclose = self.datas[0].close保存收盘价的地址。<br>在每次数据源更新时都会调用策略的next()成员函数。<br>接着在策略中增加一些逻辑。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">    self.log(<span class="string">&quot;Close, %.2f&quot;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">    <span class="comment"># 今天收盘价比昨天低</span></span><br><span class="line">    <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &lt; self.dataclose[-<span class="number">1</span>]:</span><br><span class="line">        <span class="comment"># 昨天收盘价比前天低</span></span><br><span class="line">        <span class="keyword">if</span> self.dataclose[-<span class="number">1</span>] &lt; self.dataclose[-<span class="number">2</span>]:</span><br><span class="line">            <span class="comment"># 买买买</span></span><br><span class="line">            self.log(<span class="string">&quot;在%.2f创建买单&quot;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">            self.buy()</span><br></pre></td></tr></table></figure>
<p>连续两天下跌就买入。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">初始资金:<span class="number">100000.00</span></span><br><span class="line"><span class="number">2019</span>-01-02, Close, <span class="number">3.02</span></span><br><span class="line"><span class="number">2019</span>-01-03, Close, <span class="number">3.02</span></span><br><span class="line"><span class="number">2019</span>-01-04, Close, <span class="number">3.09</span></span><br><span class="line"><span class="number">2019</span>-01-07, Close, <span class="number">3.11</span></span><br><span class="line"><span class="number">2019</span>-01-08, Close, <span class="number">3.11</span></span><br><span class="line"><span class="number">2019</span>-01-09, Close, <span class="number">3.13</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">10</span>, Close, <span class="number">3.13</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">11</span>, Close, <span class="number">3.16</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">14</span>, Close, <span class="number">3.13</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">15</span>, Close, <span class="number">3.19</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">16</span>, Close, <span class="number">3.13</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">17</span>, Close, <span class="number">3.11</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">17</span>, 在<span class="number">3.11</span>创建买单</span><br><span class="line">......</span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">20</span>, 在<span class="number">4.02</span>创建买单</span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">23</span>, Close, <span class="number">3.96</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">23</span>, 在<span class="number">3.96</span>创建买单</span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">24</span>, Close, <span class="number">3.98</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">25</span>, Close, <span class="number">3.99</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">26</span>, Close, <span class="number">4.02</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">27</span>, Close, <span class="number">4.02</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">30</span>, Close, <span class="number">4.08</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, Close, <span class="number">4.10</span></span><br><span class="line">期末资金:<span class="number">100014.36</span></span><br></pre></td></tr></table></figure>
<p>现在的问题是不知道买单何时执行，成交价多少。<br>在默认情况下，购买self.datas[0]的证券，买入量固定为1股每次，框架在买入指令下达后的下一个交易日以开盘价执行交易，没有考虑交易成本。这些都可以改变的。<br>接下来考虑卖出。框架策略有position属性，保存仓位。买卖命令都返回created命令(还没有执行)。通过策略的notify方法可以得到交易状态改变的通知。数据源的每个bar的时间单位并没有确定，天，周，月等都可以。<br>下面修改策略，在买入5个交易周期后卖出。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt=<span class="literal">None</span></span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;log记录&#x27;&#x27;&#x27;</span></span><br><span class="line">        dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">        print(<span class="string">&#x27;%s, %s&#x27;</span> % (dt.isoformat(), txt))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">        <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.log(<span class="string">&#x27;执行买入, 价格%.2f&#x27;</span> % order.executed.price)</span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.log(<span class="string">&#x27;执行卖出, 价格%.2f&#x27;</span> % order.executed.price)</span><br><span class="line"></span><br><span class="line">            self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">            self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 输出持仓</span></span><br><span class="line">        self.log(<span class="string">&#x27;持仓 %.2f&#x27;</span> % self.position.size)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有交易在进行，不能提交第二个</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有持仓</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.position:</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 没有持仓，检查是否达到买入条件</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &lt; self.dataclose[-<span class="number">1</span>]:</span><br><span class="line">                    <span class="keyword">if</span> self.dataclose[-<span class="number">1</span>] &lt; self.dataclose[-<span class="number">2</span>]:</span><br><span class="line">                        <span class="comment"># 买买买，以默认参数</span></span><br><span class="line">                        self.log(<span class="string">&#x27;买单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                        <span class="comment"># 创建买单</span></span><br><span class="line">                        self.order = self.buy()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 已经有持仓了，卖出</span></span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(self) &gt;= (self.bar_executed + <span class="number">5</span>):</span><br><span class="line">                <span class="comment"># 卖卖卖，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;卖单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建卖单</span></span><br><span class="line">                self.order = self.sell()</span><br></pre></td></tr></table></figure>
<p>结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">初始资金:<span class="number">100000.00</span></span><br><span class="line"><span class="number">2019</span>-01-02, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-03, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-04, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-07, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-08, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-09, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">10</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">11</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">14</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">15</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">16</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">17</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">17</span>, 买单创建, 价格<span class="number">3.11</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">18</span>, 执行买入, 价格<span class="number">3.12</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">18</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">21</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">22</span>, 持仓 <span class="number">1.00</span></span><br><span class="line">……</span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">25</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">26</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">27</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">30</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, 卖单创建, 价格<span class="number">4.10</span></span><br><span class="line">期末资金:<span class="number">100000.80</span></span><br></pre></td></tr></table></figure>
<p>下面再加上手续费，费率0.1%。<br>用cerebro.broker.setcommission(commission=0.001)<br>并在策略里输出手续费。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt=<span class="literal">None</span></span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;log记录&#x27;&#x27;&#x27;</span></span><br><span class="line">        dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">        print(<span class="string">&#x27;%s, %s&#x27;</span> % (dt.isoformat(), txt))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">        self.buyprice = <span class="literal">None</span></span><br><span class="line">        self.buycomm = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">        <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line"></span><br><span class="line">            self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">            self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_trade</span>(<span class="params">self, trade</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> trade.isclosed:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        self.log(<span class="string">&#x27;操作收益%.2f, 成本%.2f&#x27;</span> % (trade.pnl, trade.pnlcomm))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 输出持仓</span></span><br><span class="line">        self.log(<span class="string">&#x27;持仓 %.2f&#x27;</span> % self.position.size)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有交易在进行，不能提交第二个</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有持仓</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.position:</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 没有持仓，检查是否达到买入条件</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &lt; self.dataclose[-<span class="number">1</span>]:</span><br><span class="line">                    <span class="keyword">if</span> self.dataclose[-<span class="number">1</span>] &lt; self.dataclose[-<span class="number">2</span>]:</span><br><span class="line">                        <span class="comment"># 买买买，以默认参数</span></span><br><span class="line">                        self.log(<span class="string">&#x27;买单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                        <span class="comment"># 创建买单</span></span><br><span class="line">                        self.order = self.buy()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 已经有持仓了，卖出</span></span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(self) &gt;= (self.bar_executed + <span class="number">5</span>):</span><br><span class="line">                <span class="comment"># 卖卖卖，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;卖单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建卖单</span></span><br><span class="line">                self.order = self.sell()</span><br></pre></td></tr></table></figure>
<p>结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">……</span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">23</span>, 操作收益<span class="number">0.09</span>, 成本<span class="number">0.08</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">23</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">23</span>, 买单创建, 价格<span class="number">3.96</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">24</span>, 执行买入, 价格: <span class="number">3.96</span>, 成本: <span class="number">3.96</span>, 手续费 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">24</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">25</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">26</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">27</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">30</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, 持仓 <span class="number">1.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, 卖单创建, 价格<span class="number">4.10</span></span><br><span class="line">期末资金:<span class="number">100000.64</span></span><br></pre></td></tr></table></figure>
<p>注意因为最后一天仍然有持仓，所以最后的收益与每次交易后收益之和的累加有差异。<br>可以在策略中定义一些参数以配置策略。<br>用Python的tuple在策略类里定义</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">    params = (</span><br><span class="line">    (<span class="string">&#x27;myparam&#x27;</span>, <span class="number">27</span>),</span><br><span class="line">    (<span class="string">&#x27;exitbars&#x27;</span>, <span class="number">5</span>),</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>然后在addstrategy中以参数形式给参数赋值。<br>cerebro.addstrategy(TestStrategy, myparam=20, exitbars=7)<br>可以用addsizer来设置交易量。<br>cerebro.addsizer(bt.sizers.FixedSize, stake=100)</p>
<p>把这些结合起来。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># backtrader的第一个策略</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line">               </span><br><span class="line">               </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    params = (</span><br><span class="line">        (<span class="string">&quot;exitbars&quot;</span>, <span class="number">5</span>),</span><br><span class="line">    )</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt=<span class="literal">None</span></span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;log记录&#x27;&#x27;&#x27;</span></span><br><span class="line">        dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">        print(<span class="string">&#x27;%s, %s&#x27;</span> % (dt.isoformat(), txt))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">        self.buyprice = <span class="literal">None</span></span><br><span class="line">        self.buycomm = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">        <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">                self.buyprice = order.executed.price</span><br><span class="line">                self.buycomm = order.executed.comm</span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line"></span><br><span class="line">            self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">            self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_trade</span>(<span class="params">self, trade</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> trade.isclosed:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        self.log(<span class="string">&#x27;操作收益%.2f, 成本%.2f&#x27;</span> % (trade.pnl, trade.pnlcomm))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 输出持仓</span></span><br><span class="line">        self.log(<span class="string">&#x27;持仓 %.2f&#x27;</span> % self.position.size)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有交易在进行，不能提交第二个</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有持仓</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.position:</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 没有持仓，检查是否达到买入条件</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &lt; self.dataclose[-<span class="number">1</span>]:</span><br><span class="line">                    <span class="keyword">if</span> self.dataclose[-<span class="number">1</span>] &lt; self.dataclose[-<span class="number">2</span>]:</span><br><span class="line">                        <span class="comment"># 买买买，以默认参数</span></span><br><span class="line">                        self.log(<span class="string">&#x27;买单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                        <span class="comment"># 创建买单</span></span><br><span class="line">                        self.order = self.buy()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 已经有持仓了，卖出</span></span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(self) &gt;= (self.bar_executed + self.params.exitbars):</span><br><span class="line">                <span class="comment"># 卖卖卖，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;卖单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建卖单</span></span><br><span class="line">                self.order = self.sell()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    cerebro = bt.Cerebro()</span><br><span class="line">    cerebro.addstrategy(TestStrategy)</span><br><span class="line">    <span class="comment"># 加载数据</span></span><br><span class="line">    start = <span class="string">&quot;2019-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2019-12-31&quot;</span></span><br><span class="line">    <span class="comment"># df = ts.get_k_data(&quot;510300&quot;, autype = &quot;qfq&quot;, start = start,  end = end)</span></span><br><span class="line">    <span class="comment"># df.to_csv(&quot;data.csv&quot;)</span></span><br><span class="line">    df = pd.read_csv(<span class="string">&quot;data.csv&quot;</span>)</span><br><span class="line">    df.index = pd.to_datetime(df.date)</span><br><span class="line">    df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">    df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">    data = bt.feeds.PandasData(dataname = df, fromdate = datetime.datetime(<span class="number">2019</span>, <span class="number">1</span>, <span class="number">1</span>), todate = datetime.datetime(<span class="number">2019</span>, <span class="number">12</span>, <span class="number">31</span>))</span><br><span class="line">    cerebro.adddata(data)</span><br><span class="line">    <span class="comment"># 设置初始资金</span></span><br><span class="line">    cerebro.broker.setcash(<span class="number">100000.0</span>)</span><br><span class="line">    cerebro.broker.setcommission(commission=<span class="number">0.001</span>)</span><br><span class="line">    cerebro.addsizer(bt.sizers.FixedSize, stake=<span class="number">100</span>)</span><br><span class="line">    print(<span class="string">&quot;初始资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    cerebro.run()</span><br><span class="line">    print(<span class="string">&quot;期末资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br></pre></td></tr></table></figure>
<p>接下来就可以增加指标了。<br>下面考虑简单移动平均线策略:<br>收盘价高于均值就买入;如果有持仓，收盘价低于均值则卖出;同时只能有一个交易。<br>用bt.indicators.MovingAverageSimple</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># backtrader的第一个策略</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line">               </span><br><span class="line">               </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    params = (</span><br><span class="line">        (<span class="string">&quot;maperiod&quot;</span>, <span class="number">15</span>),</span><br><span class="line">    )</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt=<span class="literal">None</span></span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;log记录&#x27;&#x27;&#x27;</span></span><br><span class="line">        dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">        print(<span class="string">&#x27;%s, %s&#x27;</span> % (dt.isoformat(), txt))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">        self.buyprice = <span class="literal">None</span></span><br><span class="line">        self.buycomm = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">        self.sma = bt.indicators.SimpleMovingAverage(self.datas[<span class="number">0</span>], period = self.params.maperiod)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">        <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">                self.buyprice = order.executed.price</span><br><span class="line">                self.buycomm = order.executed.comm</span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line"></span><br><span class="line">            self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">            self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_trade</span>(<span class="params">self, trade</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> trade.isclosed:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        self.log(<span class="string">&#x27;操作收益%.2f, 成本%.2f&#x27;</span> % (trade.pnl, trade.pnlcomm))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 输出持仓</span></span><br><span class="line">        self.log(<span class="string">&#x27;持仓 %.2f&#x27;</span> % self.position.size)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有交易在进行，不能提交第二个</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有持仓</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.position:</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 没有持仓，检查是否达到买入条件</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &gt; self.sma[<span class="number">0</span>]:</span><br><span class="line">                <span class="comment"># 买买买，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;买单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建买单</span></span><br><span class="line">                self.order = self.buy()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 已经有持仓了，股价低于平均价格，卖出</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &lt; self.sma[<span class="number">0</span>]:</span><br><span class="line">                <span class="comment"># 卖卖卖，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;卖单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建卖单</span></span><br><span class="line">                self.order = self.sell()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    cerebro = bt.Cerebro()</span><br><span class="line">    cerebro.addstrategy(TestStrategy)</span><br><span class="line">    <span class="comment"># 加载数据</span></span><br><span class="line">    start = <span class="string">&quot;2019-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2019-12-31&quot;</span></span><br><span class="line">    <span class="comment"># df = ts.get_k_data(&quot;510300&quot;, autype = &quot;qfq&quot;, start = start,  end = end)</span></span><br><span class="line">    <span class="comment"># df.to_csv(&quot;data.csv&quot;)</span></span><br><span class="line">    df = pd.read_csv(<span class="string">&quot;data.csv&quot;</span>)</span><br><span class="line">    df.index = pd.to_datetime(df.date)</span><br><span class="line">    df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">    df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">    data = bt.feeds.PandasData(dataname = df, fromdate = datetime.datetime(<span class="number">2019</span>, <span class="number">1</span>, <span class="number">1</span>), todate = datetime.datetime(<span class="number">2019</span>, <span class="number">12</span>, <span class="number">31</span>))</span><br><span class="line">    cerebro.adddata(data)</span><br><span class="line">    <span class="comment"># 设置初始资金</span></span><br><span class="line">    cerebro.broker.setcash(<span class="number">1000.0</span>)</span><br><span class="line">    cerebro.broker.setcommission(commission=<span class="number">0.001</span>)</span><br><span class="line">    cerebro.addsizer(bt.sizers.FixedSize, stake=<span class="number">100</span>)</span><br><span class="line">    print(<span class="string">&quot;初始资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    cerebro.run()</span><br><span class="line">    print(<span class="string">&quot;期末资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br></pre></td></tr></table></figure>
<p>结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">……</span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">11</span>, 卖单创建, 价格<span class="number">3.90</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">12</span>, 执行卖出, 价格: <span class="number">3.90</span>, 成本: <span class="number">394.40</span>, 手续 费 <span class="number">0.39</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">12</span>, 操作收益-<span class="number">4.30</span>, 成本-<span class="number">5.08</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">12</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">13</span>, 持仓 <span class="number">0.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">13</span>, 买单创建, 价格<span class="number">3.97</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">16</span>, 执行买入, 价格: <span class="number">3.97</span>, 成本: <span class="number">396.70</span>, 手续 费 <span class="number">0.40</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">16</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">17</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">18</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">19</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">20</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">23</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">24</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">25</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">26</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">27</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">30</span>, 持仓 <span class="number">100.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, 持仓 <span class="number">100.00</span></span><br><span class="line">期末资金:<span class="number">1055.60</span></span><br></pre></td></tr></table></figure>
<p>注意是从第15个交易日开始交易的。框架假设所使用的指标是已经准备好的，当指标没有准备好时，交易不会开始。<br>可视化，用cerebro.plot()完成。<br>为了画更多的图像，可以加入更多的均线等指标。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># backtrader的第一个策略</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line">               </span><br><span class="line">               </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    params = (</span><br><span class="line">        (<span class="string">&quot;maperiod&quot;</span>, <span class="number">15</span>),</span><br><span class="line">    )</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt=<span class="literal">None</span></span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;log记录&#x27;&#x27;&#x27;</span></span><br><span class="line">        dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">        print(<span class="string">&#x27;%s, %s&#x27;</span> % (dt.isoformat(), txt))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">        self.buyprice = <span class="literal">None</span></span><br><span class="line">        self.buycomm = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">        self.sma = bt.indicators.SimpleMovingAverage(self.datas[<span class="number">0</span>], period = self.params.maperiod)</span><br><span class="line">        <span class="comment"># 一些要画的指标</span></span><br><span class="line">        bt.indicators.ExponentialMovingAverage(self.datas[<span class="number">0</span>], period=<span class="number">25</span>)</span><br><span class="line">        bt.indicators.WeightedMovingAverage(self.datas[<span class="number">0</span>], period=<span class="number">25</span>, subplot=<span class="literal">True</span>)</span><br><span class="line">        bt.indicators.StochasticSlow(self.datas[<span class="number">0</span>])</span><br><span class="line">        bt.indicators.MACDHisto(self.datas[<span class="number">0</span>])</span><br><span class="line">        rsi = bt.indicators.RSI(self.datas[<span class="number">0</span>])</span><br><span class="line">        bt.indicators.SmoothedMovingAverage(rsi, period=<span class="number">10</span>)</span><br><span class="line">        bt.indicators.ATR(self.datas[<span class="number">0</span>], plot = <span class="literal">False</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">        <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">                self.buyprice = order.executed.price</span><br><span class="line">                self.buycomm = order.executed.comm</span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line"></span><br><span class="line">            self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">            self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_trade</span>(<span class="params">self, trade</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> trade.isclosed:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        self.log(<span class="string">&#x27;操作收益%.2f, 成本%.2f&#x27;</span> % (trade.pnl, trade.pnlcomm))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 输出持仓</span></span><br><span class="line">        self.log(<span class="string">&#x27;持仓 %.2f&#x27;</span> % self.position.size)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有交易在进行，不能提交第二个</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有持仓</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.position:</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 没有持仓，检查是否达到买入条件</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &gt; self.sma[<span class="number">0</span>]:</span><br><span class="line">                <span class="comment"># 买买买，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;买单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建买单</span></span><br><span class="line">                self.order = self.buy()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 已经有持仓了，股价低于平均价格，卖出</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &lt; self.sma[<span class="number">0</span>]:</span><br><span class="line">                <span class="comment"># 卖卖卖，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;卖单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建卖单</span></span><br><span class="line">                self.order = self.sell()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    cerebro = bt.Cerebro()</span><br><span class="line">    cerebro.addstrategy(TestStrategy)</span><br><span class="line">    <span class="comment"># 加载数据</span></span><br><span class="line">    start = <span class="string">&quot;2019-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2019-12-31&quot;</span></span><br><span class="line">    <span class="comment"># df = ts.get_k_data(&quot;510300&quot;, autype = &quot;qfq&quot;, start = start,  end = end)</span></span><br><span class="line">    <span class="comment"># df.to_csv(&quot;data.csv&quot;)</span></span><br><span class="line">    df = pd.read_csv(<span class="string">&quot;data.csv&quot;</span>)</span><br><span class="line">    df.index = pd.to_datetime(df.date)</span><br><span class="line">    df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">    df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">    data = bt.feeds.PandasData(dataname = df, fromdate = datetime.datetime(<span class="number">2019</span>, <span class="number">1</span>, <span class="number">1</span>), todate = datetime.datetime(<span class="number">2019</span>, <span class="number">12</span>, <span class="number">31</span>))</span><br><span class="line">    cerebro.adddata(data)</span><br><span class="line">    <span class="comment"># 设置初始资金</span></span><br><span class="line">    cerebro.broker.setcash(<span class="number">1000.0</span>)</span><br><span class="line">    cerebro.broker.setcommission(commission=<span class="number">0.001</span>)</span><br><span class="line">    cerebro.addsizer(bt.sizers.FixedSize, stake=<span class="number">100</span>)</span><br><span class="line">    print(<span class="string">&quot;初始资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    cerebro.run()</span><br><span class="line">    print(<span class="string">&quot;期末资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    cerebro.plot()</span><br><span class="line">    plt.savefig(<span class="string">&quot;result.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/44/01.png"><br>尽管交易逻辑没变，结果却变了，因为数据不一样了。2月25日才计算完所有指标开始交易。<br>最后来看看优化。不同的市场和交易品种可能有不同的参数。可以在一个范围内改变参数取值来看回测结果。但注意不要过度优化，那样好的结果只适合于特定的数据集。还是用上面的移动均线策略做例子，改变均线周期。<br>用cerebro.optstrategy(TestStrategy, maperiod = range(10, 31)) 来代替addstrategy()。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># backtrader的第一个策略</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">import</span> sys</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line">               </span><br><span class="line">               </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    params = (</span><br><span class="line">        (<span class="string">&quot;maperiod&quot;</span>, <span class="number">15</span>),</span><br><span class="line">        (<span class="string">&quot;printlog&quot;</span>, <span class="literal">False</span>),</span><br><span class="line">    )</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt=<span class="literal">None</span>, doprint=<span class="literal">False</span></span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;log记录&#x27;&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">if</span> self.params.printlog <span class="keyword">or</span> doprint:</span><br><span class="line">            dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">            print(<span class="string">&#x27;%s, %s&#x27;</span> % (dt.isoformat(), txt))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">        self.buyprice = <span class="literal">None</span></span><br><span class="line">        self.buycomm = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">        self.sma = bt.indicators.SimpleMovingAverage(self.datas[<span class="number">0</span>], period = self.params.maperiod)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">        <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">                self.buyprice = order.executed.price</span><br><span class="line">                self.buycomm = order.executed.comm</span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line"></span><br><span class="line">            self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">            self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_trade</span>(<span class="params">self, trade</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> trade.isclosed:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        self.log(<span class="string">&#x27;操作收益%.2f, 成本%.2f&#x27;</span> % (trade.pnl, trade.pnlcomm))</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 输出持仓</span></span><br><span class="line">        self.log(<span class="string">&#x27;持仓 %.2f&#x27;</span> % self.position.size)</span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有交易在进行，不能提交第二个</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查是否有持仓</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.position:</span><br><span class="line"></span><br><span class="line">            <span class="comment"># 没有持仓，检查是否达到买入条件</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &gt; self.sma[<span class="number">0</span>]:</span><br><span class="line">                <span class="comment"># 买买买，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;买单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建买单</span></span><br><span class="line">                self.order = self.buy()</span><br><span class="line"></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 已经有持仓了，股价低于平均价格，卖出</span></span><br><span class="line">            <span class="keyword">if</span> self.dataclose[<span class="number">0</span>] &lt; self.sma[<span class="number">0</span>]:</span><br><span class="line">                <span class="comment"># 卖卖卖，以默认参数</span></span><br><span class="line">                self.log(<span class="string">&#x27;卖单创建, 价格%.2f&#x27;</span> % self.dataclose[<span class="number">0</span>])</span><br><span class="line">                <span class="comment"># 创建卖单</span></span><br><span class="line">                self.order = self.sell()</span><br><span class="line">               </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">stop</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.log(<span class="string">&#x27;(MA Period %2d) Ending Value %.2f&#x27;</span> % (self.params.maperiod, self.broker.getvalue()), doprint=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    cerebro = bt.Cerebro()</span><br><span class="line">    <span class="comment"># cerebro.addstrategy(TestStrategy)</span></span><br><span class="line">    <span class="comment"># 用参数优化代替添加策略</span></span><br><span class="line">    strats = cerebro.optstrategy(TestStrategy, maperiod = <span class="built_in">range</span>(<span class="number">10</span>, <span class="number">31</span>))</span><br><span class="line">    <span class="comment"># 加载数据</span></span><br><span class="line">    start = <span class="string">&quot;2019-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2019-12-31&quot;</span></span><br><span class="line">    <span class="comment"># df = ts.get_k_data(&quot;510300&quot;, autype = &quot;qfq&quot;, start = start,  end = end)</span></span><br><span class="line">    <span class="comment"># df.to_csv(&quot;data.csv&quot;)</span></span><br><span class="line">    df = pd.read_csv(<span class="string">&quot;data.csv&quot;</span>)</span><br><span class="line">    df.index = pd.to_datetime(df.date)</span><br><span class="line">    df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">    df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">    data = bt.feeds.PandasData(dataname = df, fromdate = datetime.datetime(<span class="number">2019</span>, <span class="number">1</span>, <span class="number">1</span>), todate = datetime.datetime(<span class="number">2019</span>, <span class="number">12</span>, <span class="number">31</span>))</span><br><span class="line">    cerebro.adddata(data)</span><br><span class="line">    <span class="comment"># 设置初始资金</span></span><br><span class="line">    cerebro.broker.setcash(<span class="number">1000.0</span>)</span><br><span class="line">    cerebro.broker.setcommission(commission=<span class="number">0.001</span>)</span><br><span class="line">    cerebro.addsizer(bt.sizers.FixedSize, stake=<span class="number">100</span>)</span><br><span class="line">    print(<span class="string">&quot;初始资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    cerebro.run(maxcpus = <span class="number">1</span>)</span><br><span class="line">    <span class="comment"># print(&quot;期末资金:%.2f&quot; % cerebro.broker.getvalue())</span></span><br><span class="line">    <span class="comment"># cerebro.plot()</span></span><br><span class="line">    <span class="comment"># plt.savefig(&quot;result.png&quot;)</span></span><br></pre></td></tr></table></figure>
<p>运行结果</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">$ python first.py</span><br><span class="line">初始资金:<span class="number">1000.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">10</span>) Ending Value <span class="number">1031.22</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">11</span>) Ending Value <span class="number">1018.49</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">12</span>) Ending Value <span class="number">1027.47</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">13</span>) Ending Value <span class="number">1038.64</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">14</span>) Ending Value <span class="number">1052.18</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">15</span>) Ending Value <span class="number">1055.60</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">16</span>) Ending Value <span class="number">1054.62</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">17</span>) Ending Value <span class="number">1058.46</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">18</span>) Ending Value <span class="number">1053.79</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">19</span>) Ending Value <span class="number">1050.40</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">20</span>) Ending Value <span class="number">1046.80</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">21</span>) Ending Value <span class="number">1042.11</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">22</span>) Ending Value <span class="number">1042.97</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">23</span>) Ending Value <span class="number">1035.79</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">24</span>) Ending Value <span class="number">1034.00</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">25</span>) Ending Value <span class="number">1030.99</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">26</span>) Ending Value <span class="number">1029.02</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">27</span>) Ending Value <span class="number">1023.43</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">28</span>) Ending Value <span class="number">1052.18</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">29</span>) Ending Value <span class="number">1040.87</span></span><br><span class="line"><span class="number">2019</span>-<span class="number">12</span>-<span class="number">31</span>, (MA Period <span class="number">30</span>) Ending Value <span class="number">1039.77</span></span><br></pre></td></tr></table></figure>
<p>用17日均线收益最高。<br>更进一步的改进:自定义指标，设置Sizer(资金管理)，交易类型(限价等)。<br>接下来打算看一遍官网的文档，写个回测实操下。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/Backtrader/" rel="tag"># Backtrader</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/06/24/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B068%E2%80%94%E2%80%94%E9%80%9A%E8%BF%87%E9%97%AE%E9%A2%98%E5%AD%A6%E7%AE%97%E6%B3%9518-%E8%AE%B0%E5%BF%86%E5%8A%9B%E5%BE%88%E5%A5%BD%EF%BC%88Memory-Serves-You-Well%EF%BC%89/" rel="next" title="量化投资学习笔记68——通过问题学算法18:记忆力很好（Memory Serves You Well）">
                <i class="fa fa-chevron-left"></i> 量化投资学习笔记68——通过问题学算法18:记忆力很好（Memory Serves You Well）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/06/27/%E4%B8%80%E8%B5%B7%E6%9D%A5%E7%94%BB%E7%89%9906%EF%BC%88%E5%A4%A7%E7%BB%93%E5%B1%80%E4%BA%86%EF%BC%89/" rel="prev" title="一起来画牙06（大结局了）">
                一起来画牙06（大结局了） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
